<template>
  <!-- 搜索区域 -->
  <div class="search-section">
    <label class="search-label">角色权限:</label>
    <div class="search-input-group">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入菜单名称"
        class="search-input"
        @input="handleSearch"
      />
      <el-button type="primary" @click="handleSearch">查询</el-button>
    </div>
  </div>
  <!-- 权限列表区域 -->
  <div class="permissions-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-icon class="is-loading"><Loading /></el-icon>
      <span>加载权限数据中...</span>
    </div>

    <!-- 权限列表 -->
    <div v-else class="permissions-list" ref="permissionsList">
      <!-- 全选 -->
      <div class="permission-item select-all">
        <el-checkbox v-model="selectAll" @change="handleSelectAll" :indeterminate="isIndeterminate">
          全选
        </el-checkbox>
      </div>

      <!-- 权限项 -->
      <div
        v-for="category in permissionsData"
        :key="category.id"
        class="permission-category"
        :class="{ highlighted: category.highlighted }"
      >
        <!-- 主分类 -->
        <div class="permission-item main-category" @click="toggleCategory(category.id)">
          <div class="category-header">
            <el-checkbox
              v-model="category.checked"
              @change="handleCategoryChange(category)"
              :indeterminate="getCategoryIndeterminate(category)"
              @click.stop
            >
              {{ category.name }}
            </el-checkbox>
            <div class="expand-icon" :class="{ expanded: category.expanded }">
              <el-icon><ArrowDown /></el-icon>
            </div>
          </div>
        </div>
        <!-- 操作权限和子菜单 -->
        <div class="actions-container" v-show="category.expanded">
          <div
            v-for="item in category.children"
            :key="item.id"
            class="action-item"
            :class="{
              highlighted: item.highlighted,
              'sub-menu': item.type !== 'button',
            }"
          >
            <!-- 子菜单 -->
            <div
              v-if="item.type !== 'button'"
              class="sub-menu-item"
              @click="toggleSubMenu(item.id)"
            >
              <div class="sub-menu-header">
                <el-checkbox
                  v-model="item.checked"
                  @change="handleSubMenuChange(item)"
                  :indeterminate="getSubMenuIndeterminate(item)"
                  @click.stop
                >
                  {{ item.name }}
                </el-checkbox>
                <div class="expand-icon" :class="{ expanded: item.expanded }">
                  <el-icon><ArrowDown /></el-icon>
                </div>
              </div>
            </div>
            <!-- 按钮权限 -->
            <div v-else class="button-item">
              <el-checkbox v-model="item.checked" @change="handleActionChange(category, item)">
                {{ item.name }}
              </el-checkbox>
            </div>

            <!-- 子菜单的操作权限 -->
            <div
              v-if="item.type !== 'button' && item.children && item.children.length > 0"
              class="sub-actions-container"
              v-show="item.expanded"
            >
              <div
                v-for="subAction in item.children"
                :key="subAction.id"
                class="sub-action-item"
                :class="{ highlighted: subAction.highlighted }"
              >
                <el-checkbox
                  v-model="subAction.checked"
                  @change="handleSubActionChange(item, subAction)"
                >
                  {{ subAction.name }}
                </el-checkbox>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowDown, Loading } from '@element-plus/icons-vue'

const router = useRouter()

// 响应式变量
const searchKeyword = ref('')
const loading = ref(false)

// 权限数据
const permissionsData = reactive([])

// API 调用函数
const fetchPermissionsData = async () => {
  try {
    loading.value = true

    // 调用后端API获取权限数据
    const response = await fetch('http://localhost:9090/menuitems/get', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        // 如果需要认证，添加相应的 headers
        // 'Authorization': `Bearer ${token}`
      },
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const result = await response.json()

    if (result.code === 200) {
      // 转换后端数据格式为前端需要的格式
      const convertedData = convertBackendDataToFrontend(result.data)
      // 清空原有数据并添加新数据
      permissionsData.splice(0, permissionsData.length, ...convertedData)
      ElMessage.success('权限数据加载成功')
    } else {
      ElMessage.error(result.message || '获取权限数据失败')
    }
  } catch (error) {
    console.error('获取权限数据失败:', error)
    ElMessage.error('获取权限数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 数据转换函数：将后端数据转换为前端需要的格式
const convertBackendDataToFrontend = (backendData) => {
  const convertMenu = (menu) => {
    const convertedMenu = {
      id: menu.strmenucode,
      name: menu.strmenuname,
      checked: false,
      expanded: true, // 默认展开
      children: [],
    }

    // 处理按钮权限
    if (menu.buttons && menu.buttons.length > 0) {
      convertedMenu.children = menu.buttons.map((button) => ({
        id: button.strbuttoncode,
        name: button.strbuttonname,
        checked: false,
        type: 'button',
      }))
    }

    // 处理子菜单
    if (menu.children && menu.children.length > 0) {
      const subMenus = menu.children.map(convertMenu)
      convertedMenu.children = [...convertedMenu.children, ...subMenus]
    }

    return convertedMenu
  }

  return backendData.map(convertMenu)
}

// 获取所有可选择的项目（主分类 + 子菜单 + 操作权限）
const getAllItems = () => {
  const items = []

  const addItems = (category) => {
    items.push(category) // 添加主分类
    if (category.children) {
      category.children.forEach((item) => {
        if (item.type === 'button') {
          items.push(item) // 添加按钮权限
        } else {
          addItems(item) // 递归添加子菜单及其子项
        }
      })
    }
  }

  permissionsData.forEach(addItems)
  return items
}

// 全选状态
const selectAll = computed({
  get() {
    const allItems = getAllItems()
    return allItems.length > 0 && allItems.every((item) => item.checked)
  },
  set() {
    // 通过 handleSelectAll 处理
  },
})

// 半选状态
const isIndeterminate = computed(() => {
  const allItems = getAllItems()
  const checkedCount = allItems.filter((item) => item.checked).length
  return checkedCount > 0 && checkedCount < allItems.length
})

// 计算主分类的半选状态
const getCategoryIndeterminate = (category) => {
  if (!category.children || category.children.length === 0) {
    return false
  }

  const checkedCount = category.children.filter((action) => action.checked).length
  return checkedCount > 0 && checkedCount < category.children.length
}

// 搜索功能
const handleSearch = () => {
  console.log('搜索:', searchKeyword.value)
}

// 切换分类展开/收缩
const toggleCategory = (categoryId) => {
  const category = permissionsData.find((cat) => cat.id === categoryId)
  if (category) {
    category.expanded = !category.expanded
  }
}

// 全选/取消全选
const handleSelectAll = (checked) => {
  const allItems = getAllItems()
  allItems.forEach((item) => {
    item.checked = checked
  })
}

// 主分类变化时，影响所有操作权限
const handleCategoryChange = (category) => {
  if (category.children) {
    category.children.forEach((action) => {
      action.checked = category.checked
    })
  }
}

// 操作权限变化时，更新主分类状态
const handleActionChange = (category, action) => {
  // 检查主分类下所有操作权限的选中状态
  if (category.children) {
    const allChecked = category.children.every((action) => action.checked)
    const someChecked = category.children.some((action) => action.checked)

    if (allChecked) {
      category.checked = true // 全部选中
    } else if (someChecked) {
      category.checked = false // 部分选中（半选状态）
    } else {
      category.checked = false // 全部未选中
    }
  }
}

// 切换子菜单展开/收缩
const toggleSubMenu = (subMenuId) => {
  // 在所有分类中查找子菜单
  permissionsData.forEach((category) => {
    if (category.children) {
      const subMenu = category.children.find((item) => item.id === subMenuId)
      if (subMenu) {
        subMenu.expanded = !subMenu.expanded
      }
    }
  })
}

// 子菜单变化时，更新父分类状态
const handleSubMenuChange = (subMenu) => {
  if (subMenu.children) {
    subMenu.children.forEach((action) => {
      action.checked = subMenu.checked
    })
  }

  // 更新主分类状态
  updateParentCategoryStatus(subMenu)
}

// 子菜单操作权限变化时，更新子菜单和父分类状态
const handleSubActionChange = (subMenu, subAction) => {
  // 检查子菜单下所有操作权限的选中状态
  if (subMenu.children) {
    const allChecked = subMenu.children.every((action) => action.checked)
    const someChecked = subMenu.children.some((action) => action.checked)

    if (allChecked) {
      subMenu.checked = true // 全部选中
    } else if (someChecked) {
      subMenu.checked = false // 部分选中（半选状态）
    } else {
      subMenu.checked = false // 全部未选中
    }
  }

  // 更新主分类状态
  updateParentCategoryStatus(subMenu)
}

// 更新父分类状态
const updateParentCategoryStatus = (subMenu) => {
  permissionsData.forEach((category) => {
    if (category.children && category.children.includes(subMenu)) {
      const allChecked = category.children.every((item) => item.checked)
      const someChecked = category.children.some((item) => item.checked)

      if (allChecked) {
        category.checked = true
      } else if (someChecked) {
        category.checked = false
      } else {
        category.checked = false
      }
    }
  })
}

// 计算子菜单的半选状态
const getSubMenuIndeterminate = (subMenu) => {
  if (!subMenu.children || subMenu.children.length === 0) {
    return false
  }

  const checkedCount = subMenu.children.filter((action) => action.checked).length
  return checkedCount > 0 && checkedCount < subMenu.children.length
}

// 组件挂载时获取权限数据
onMounted(() => {
  fetchPermissionsData()
})
</script>

<style scoped>
/* 搜索区域样式 */
.search-section {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 8px;
}

.search-label {
  font-weight: 500;
  margin-right: 12px;
  color: #303133;
}

.search-input-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-input {
  width: 300px;
}

/* 权限容器样式 */
.permissions-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.loading-container {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
  color: #909399;
}

.loading-container .el-icon {
  margin-right: 8px;
  font-size: 18px;
}

/* 权限列表样式 */
.permissions-list {
  max-height: 600px;
  overflow-y: auto;
}

.permission-category {
  border-bottom: 1px solid #ebeef5;
}

.permission-category:last-child {
  border-bottom: none;
}

.permission-item {
  padding: 16px 20px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.permission-item:hover {
  background-color: #f5f7fa;
}

.permission-item.select-all {
  background-color: #f0f9ff;
  border-bottom: 2px solid #409eff;
  font-weight: 600;
}

.permission-item.main-category {
  background-color: #fafafa;
  border-left: 4px solid #409eff;
}

.category-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.expand-icon {
  transition: transform 0.3s;
  color: #909399;
}

.expand-icon.expanded {
  transform: rotate(180deg);
}

/* 操作权限容器 */
.actions-container {
  background-color: #fafbfc;
  border-top: 1px solid #ebeef5;
}

.action-item {
  padding: 12px 20px 12px 40px;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.3s;
}

.action-item:last-child {
  border-bottom: none;
}

.action-item:hover {
  background-color: #f5f7fa;
}

.action-item.highlighted {
  background-color: #e6f7ff;
}

/* 子菜单样式 */
.action-item.sub-menu {
  background-color: #f8f9fa;
  border-left: 3px solid #67c23a;
}

.sub-menu-item {
  cursor: pointer;
}

.sub-menu-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

/* 子菜单操作权限容器 */
.sub-actions-container {
  background-color: #f0f2f5;
  margin-left: 20px;
  border-left: 2px solid #e4e7ed;
}

.sub-action-item {
  padding: 8px 20px 8px 40px;
  border-bottom: 1px solid #e4e7ed;
  font-size: 14px;
  color: #606266;
}

.sub-action-item:last-child {
  border-bottom: none;
}

.sub-action-item:hover {
  background-color: #f5f7fa;
}

.sub-action-item.highlighted {
  background-color: #e6f7ff;
}

/* 按钮权限样式 */
.button-item {
  padding: 8px 0;
  font-size: 14px;
  color: #606266;
}

/* 高亮样式 */
.highlighted {
  background-color: #e6f7ff !important;
  border-left-color: #409eff !important;
}

/* 滚动条样式 */
.permissions-list::-webkit-scrollbar {
  width: 6px;
}

.permissions-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.permissions-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.permissions-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
